package quangtqServlet;

import beans.Mail;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import quangtq.MailPagingRemote;

@WebServlet(name="MailPagingServlet", urlPatterns={"/MailPagingServlet"})
public class MailPagingServlet extends HttpServlet {
    @EJB
    private MailPagingRemote mailPaging;
   
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    {
        // key is the parameter passed in from the JavaScript
        // variable named url (see index.html)
        String page = req.getParameter("page");
        String isInbox = req.getParameter("isInbox");
        StringBuffer returnXML = null;

        if (page != null)
        {
            String userName = (String)req.getSession().getAttribute("username");

            ArrayList<Mail> lstMail = mailPaging.mailRange(Integer.parseInt(page), 10, userName, 
                    isInbox.equals("1") ? true : false);

            Iterator<Mail> iterator = lstMail.iterator();

            returnXML = new StringBuffer("\r\n<mails>");
            while(iterator.hasNext())
            {
                Mail mail = iterator.next();
                String subject = mail.getSubject();
                if(subject.equals(""))
                {
                    subject = "no subject";
                }

                returnXML.append("\r\n<mail>");

                returnXML.append("\r\n<mailID>" + mail.getMailID() + "</mailID>");
                returnXML.append("\r\n<fromUser>" + mail.getFromUser() + "</fromUser>");
                returnXML.append("\r\n<subject>" + subject + "</subject>");

                returnXML.append("\r\n</mail>");
            }
            returnXML.append("\r\n</mails>");

            // set up the response
            res.setContentType("text/xml");
            res.setHeader("Cache-Control", "no-cache");
            // write out the XML string
            res.getWriter().write(returnXML.toString( ));
        }
        else
        {
            // if key comes back as a null, return a question mark
            res.setContentType("text/xml");
            res.setHeader("Cache-Control", "no-cache");
            res.getWriter().write("?");
        }

    }
}
